package com.xunqi.orderservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.wxpay.sdk.WXPayUtil;
import com.xunqi.commonutils.R;
import com.xunqi.orderservice.entity.Order;
import com.xunqi.orderservice.entity.PayLog;
import com.xunqi.orderservice.enums.OrderStatusEnums;
import com.xunqi.orderservice.enums.PayTypeEnums;
import com.xunqi.orderservice.feign.CourseFeign;
import com.xunqi.orderservice.mapper.PayLogMapper;
import com.xunqi.orderservice.service.OrderService;
import com.xunqi.orderservice.service.PayLogService;
import com.xunqi.orderservice.utils.HttpClient;
import com.xunqi.servicebase.exception.GuliException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 支付日志表 服务实现类
 * </p>
 *
 * @author 夏沫止水
 * @since 2020-08-12
 */
@Service
public class PayLogServiceImpl extends ServiceImpl<PayLogMapper, PayLog> implements PayLogService {

    @Autowired
    private OrderService orderService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private CourseFeign courseFeign;

    /**
     * 根据订单号生成微信支付二维码接口
     * @param orderNo
     * @return
     */
    @Override
    public Map createNative(String orderNo) {

        try {
            //1、根据订单号查询订单信息
            Order orderInfo = this.orderService.getOne(new QueryWrapper<Order>().eq("order_no", orderNo));

            if (orderInfo == null) {
                throw new GuliException(20001,"订单不存在");
            }

            //2、使用map集合设置生成二维码需要参数
            Map m = new HashMap<>();
            m.put("appid", "wx74862e0dfcf69954");
            m.put("mch_id", "1558950191");
            m.put("nonce_str", WXPayUtil.generateNonceStr());
            m.put("body", orderInfo.getCourseTitle());
            m.put("out_trade_no", orderNo);
            m.put("total_fee", orderInfo.getTotalFee().multiply(new
                    BigDecimal("100")).longValue()+"");
            m.put("spbill_create_ip", "127.0.0.1");
            m.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify\n");
            m.put("trade_type", "NATIVE");

            //2、 HTTPClient来根据URL访问第三方接口并且传递参数
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            //client设置参数
            client.setXmlParam(WXPayUtil.generateSignedXml(m, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);
            client.post();

            //3、返回第三方的数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);

            //4、封装返回结果集
            Map map = new HashMap<>();
            map.put("out_trade_no", orderNo);
            map.put("course_id", orderInfo.getCourseId());
            map.put("total_fee", orderInfo.getTotalFee());
            map.put("result_code", resultMap.get("result_code"));       //返回二维码操作状态码
            map.put("code_url", resultMap.get("code_url"));             //二维码地址
            //微信支付二维码2小时过期，可采取2小时未支付取消订单
            // stringRedisTemplate.opsForValue().set(orderNo, map, 120, TimeUnit.MINUTES);
            return map;

        } catch (Exception e) {
            e.printStackTrace();
            throw new GuliException(20001,"生成二维码失败");
        }
    }

    /**
     * 根据订单号查询订单支付状态
     * @param orderNo
     * @return
     */
    @Override
    public Map<String, String> queryPayStatus(String orderNo) {

        try {
            //1、封装参数
            Map m = new HashMap<>();
            m.put("appid", "wx74862e0dfcf69954");
            m.put("mch_id", "1558950191");
            m.put("out_trade_no", orderNo);
            m.put("nonce_str", WXPayUtil.generateNonceStr());

            //2、设置请求
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(m, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);
            client.post();

            //3、返回第三方的数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);

            //6、转成Map
            // 7、返回
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 向支付表添加记录，更新订单状态
     * @param map
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateOrderStatus(Map<String, String> map) {

        //获取订单id
        String orderNo = map.get("out_trade_no");

        //根据订单id查询订单信息
        Order orderInfo = this.orderService.getOne(new QueryWrapper<Order>().eq("order_no", orderNo));
        //判断订单状态是否已支付
        if (orderInfo.getStatus().equals(OrderStatusEnums.PAYMENT.getCode())) { //已支付
            return;
        }

        //未支付改变支付状态
        orderInfo.setStatus(OrderStatusEnums.PAYMENT.getCode());
        //更新到数据库中
        orderService.updateById(orderInfo);

        //课程销售数量+1
        R courseR = courseFeign.addBuyCount(orderInfo.getCourseId());

        if (courseR.getCode() == 20000) {
            //记录支付日志
            PayLog payLog = new PayLog();
            payLog.setOrderNo(orderNo);
            payLog.setPayTime(new Date());
            payLog.setTotalFee(orderInfo.getTotalFee());
            payLog.setTransactionId(null);
            payLog.setTradeState("SUCCESS");
            payLog.setPayType(PayTypeEnums.WXTYPE.getCode());
            payLog.setAttr(JSONObject.toJSONString(map));
            //插入到数据库中
            this.baseMapper.insert(payLog);
        }

    }
}
